Flask Framework

Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug, WSGI toolkit and Jinja2 template engine. Both are Pocco projects.

Installation

Installing flask inside virtualenv

pip install virtualenv
cd <project_folder>
virtualenv venv
venv/bin/activate

pip install Flask

Application

Lets create a basic application in flask. Showcasing function name in telugu language.

"""."""
from flask import Flask


app = Flask(__name__)


@app.route('/', methods=['GET'])
def రేమకు_స్వాగతం():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


if __name__ == '__main__':
    app.run()

Lets discuss its various sections,

First we import Flask from flask application, then we create an app from Flask, next we create some routes, and finally we execute the created flask app.

Application in debug mode

"""."""
from flask import Flask


app = Flask(__name__)


@app.route('/', methods=['GET'])
def రేమకు_స్వాగతం():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


if __name__ == '__main__':
    app.run(debug=True)

Running the applicataion

python <flask_app.py>
Externally Visible Server
flask run --host=0.0.0.0

or

"""."""
from flask import Flask


app = Flask(__name__)


@app.route('/', methods=['GET'])
def రేమకు_స్వాగతం():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


if __name__ == '__main__':
    app.run(debug=True, port=20202, host="0.0.0.0")
python <flask_app.py>

Routing

route() decorator of the Flask class tells the application which URL/request type should be mapped to the below function. Its syntax is as follows

app.route(rule, options)

  • rule: It represents the URL binding with the function, such as /login, /register etc.
  • options: The options are forwarded to the underlying class:~werkzeug.routing.Rule object. It contains a parameter methods which is a list of methods this rule should be limited to (GET, POST etc.). By default a rule just listens for GET (and implicitly HEAD)

Most modern web frameworks employ routing technique in mapping application URLs to functions.

"""."""
from flask import Flask


app = Flask(__name__)


@app.route('/telugu')
def రేమకు_స్వాగతం():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


@app.route('/tamil')
def நல்வரவு():
    """swagatham in tamil language."""
    return "நல்வரவு"


@app.route('/kannada')
def ಸುಸ್ವಾಗತ():
    """swagatham in kannada language."""
    return "ಸುಸ್ವಾಗತ"


@app.route('/german')
def Willkommen():
    """swagatham in german language."""
    return "Willkommen"


@app.route('/Hebrew')
def Shalom():
    """swagatham in Hebrew language."""
    return "Shalom"


if __name__ == '__main__':
    app.run()

We can also bind the urls with functions using add_url_rule() as shown below

"""Example using add_url_rule."""
from flask import Flask


def రేమకు_స్వాగతం():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


def நல்வரவு():
    """swagatham in tamil language."""
    return "நல்வரவு"


def ಸುಸ್ವಾಗತ():
    """swagatham in kannada language."""
    return "ಸುಸ್ವಾಗತ"


if __name__ == '__main__':
    rules = {
        'telugu': రేమకు_స్వాగతం,
        'tamil': நல்வரவு,
        'kannada': ಸುಸ್ವಾಗತ
    }

    app = Flask(__name__)
    for rule, func in rules.items():
        print(rule, func)
        app.add_url_rule('/' + rule, None, func)
    app.run()

Variable Rules

Flask can process the variable parts to a URL by marking these special sections as which are then passed as a keyword argument to the function. Also a converter can be used by specifying a rule with converter:variable_name as shown in the examples below

"""Example using add_url_rule."""
from flask import Flask


app = Flask(__name__)


@app.route('/welcome:<language>')
def select_welcome(language):
    rules = {
        'telugu': రేమకు_స్వాగతం,
        'tamil': நல்வரவு,
        'kannada': ಸುಸ್ವಾಗತ
    }
    print(language)
    return rules[language]()


def రేమకు_స్వాగతం():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


def நல்வரவு():
    """swagatham in tamil language."""
    return "நல்வரவு"


def ಸುಸ್ವಾಗತ():
    """swagatham in kannada language."""
    return "ಸುಸ್ವಾಗತ"


if __name__ == '__main__':
    app.run()

We can also define the datatype of the parameter using the following table

string accepts any text without a slash (the default)
int integers
float floating point values
path similar to default but also accepts slashes
any matches one of the items provided
uuid accepts UUID strings
"""Example for variable rules."""
# variable_rules_2.py

from flask import Flask
from random import randint, uniform

app = Flask(__name__)


@app.route('/get_rand:<int:num>')
def get_random_int(num):
    print("get_random_int", num)
    return str(randint(1, int(num)))


@app.route('/get_rand:<float:num>')
def get_random_float(num):
    print(num)
    return str(uniform(0, float(num)))


@app.route("/get_rand:<num>")
def get_any_rand(num):
    return "not found"


if __name__ == '__main__':
    app.run()

URL Building

To build a URL to a specific function you can use the url_for() function. It accepts the name of the function as first argument and a number of keyword arguments, each corresponding to the variable part of the URL rule. Unknown variable parts are appended to the URL as query parameters.

"""."""
from flask import Flask
from flask import abort, redirect, url_for

app = Flask(__name__)


@app.route('/telugu')
def telugu():
    """swagatham in telugu language."""
    return "రేమకు స్వాగతం"


@app.route('/tamil')
def tamil():
    """swagatham in tamil language."""
    return "நல்வரவு"


@app.route('/kannada')
def kannada():
    """swagatham in kannada language."""
    return "ಸುಸ್ವಾಗತ"


@app.route('/welcome:<language>')
def welcome(language):
    return redirect(url_for(language.lower()))


if __name__ == '__main__':
    app.run()

HTTP methods

HTTP protocol supports multiple methods for accessing URLs. By default, GET requests are handled for any requests, using methods argument to the route() decorator other methods can also be served as shown in the examples below

from flask import request

@app.route('/logmein', methods=['GET', 'POST'])
def logmein():
    if request.method == 'POST':
        validate_login(request.data)
    else:
        show_login()

Methods

  • GET: The browser tells the server to just get the information stored on that page and send it. This is probably the most common method.
  • HEAD: The browser tells the server to get the information, but it is only interested in the headers, not the content of the page. An application is supposed to handle that as if a GET request was received but to not deliver the actual content. In Flask you don’t have to deal with that at all, the underlying Werkzeug library handles that for you.
  • POST: The browser tells the server that it wants to post some new information to that URL and that the server must ensure the data is stored and only stored once. This is how HTML forms usually transmit data to the server.
  • PUT: Similar to POST but the server might trigger the store procedure multiple times by overwriting the old values more than once. Now you might be asking why this is useful, but there are some good reasons to do it this way. Consider that the connection is lost during transmission: in this situation a system between the browser and the server might receive the request safely a second time without breaking things. With POST that would not be possible because it must only be triggered once.
  • DELETE: Remove the information at the given location.
"""Echo Implementation in flask."""
from flask import Flask, request


app = Flask(__name__)


@app.route('/echo', methods=['GET', 'POST'])
def echo():
    if request.method == 'POST':
        print(request.form)
        return request.form['echo']
    else:
        return """<html>
        <body>
           <form action="/echo" method="post">
              Text to echo: <input type="text" name="echo"><br>
              <input type="submit" value="Submit">
            </form>
        </body></html>
        """


if __name__ == '__main__':
    app.run(debug=True)

Rendering Templates

goto jinja2 section of the tutorial

Static Files

Web server also host many static files like css, js, png, jpg, mov, avi, swf etc. Flask provide a way to handle these types of files. A folder named static can be created under project structure where all these types of files can be stored.

These files can be accessed using the following code.

url_for('static', filename='style.css')

In [ ]:


In [3]:
### Request Object

In [ ]:


In [ ]:
### Sending Form Data to Template

In [ ]:


In [ ]:
### Cookies

In [ ]:


In [ ]:
### Sessions

In [ ]:


In [5]:
### Redirect and Errors

In [ ]:


In [ ]:
### Message Flashing

In [ ]:


In [ ]:
### File Uploading

In [ ]:


In [6]:
### Extensions

In [ ]:


In [ ]:
### Mail

In [ ]:


In [7]:
### WTF

In [ ]:


In [ ]:
### SQLite

In [ ]:


In [8]:
### SQLAlchemy

In [ ]:


In [ ]:
### Sijax

In [ ]:


In [ ]:
### Deployment

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:

Reference